<template>
    <div>
        <ly-dialog v-model="dialogVisible" :title="dialogTitle" width="660px" :before-close="handleClose">
            <el-form :inline="false" :model="formData" :rules="rules" ref="rulesForm" label-position="right" label-width="auto">
                <el-form-item label="角色名称：" prop="name">
                    <el-input v-model.trim="formData.name" style="width: 100%"></el-input>
                </el-form-item>
                <el-form-item label="权限字符：" prop="key">
                    <el-input v-model.trim="formData.key" style="width: 100%"></el-input>
                </el-form-item>
                <el-form-item label="角色描述：" prop="description">
                    <el-input 
                        v-model.trim="formData.description" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入角色描述"
                        style="width: 100%">
                    </el-input>
                </el-form-item>
                <el-form-item label="数据权限范围：" prop="data_scope">
                    <el-select v-model="formData.data_scope" placeholder="请选择数据权限范围" style="width: 100%">
                        <el-option
                            v-for="item in dataScopeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="是否管理员：" prop="admin">
                    <el-radio-group v-model="formData.admin" style="width: 300px">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="状态：" prop="status">
                    <el-radio-group v-model="formData.status" style="width: 300px">
                        <el-radio :label="true">启用</el-radio>
                        <el-radio :label="false">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                    <el-input-number v-model="formData.sort" :min="0" :max="9999"></el-input-number>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleClose" :loading="loadingSave">取消</el-button>
                <el-button type="primary" @click="submitData" :loading="loadingSave">确定</el-button>
            </template>
        </ly-dialog>
    </div>
</template>

<script>
    import {apiSystemRoleEdit,apiSystemRoleAdd,apiSystemRoleDataScopeOptions} from '@/api/api'
    import LyDialog from "@/components/dialog/dialog.vue";
    export default {
        components: {LyDialog},
        emits: ['refreshData'],
        name: "addRole",
        data() {
            return {
                dialogVisible:false,
                loadingSave:false,
                dialogTitle:'',
                formData:{
                    id: null,  // 添加ID字段
                    name:'',
                    key:'',
                    description:'',
                    data_scope:'dept',  // 默认部门权限
                    status:true,
                    sort:0,
                },
                dataScopeOptions: [], // 数据权限选项
                rules:{
                    name: [
                        {required: true, message: '请输入角色名称',trigger: 'blur'}
                    ],
                    key: [
                        {required: true, message: '请输入权限字符',trigger: 'blur'}
                    ],
                    data_scope: [
                        {required: true, message: '请选择数据权限范围',trigger: 'blur'}
                    ],
                    status: [
                        {required: true, message: '请选择状态',trigger: 'blur'}
                    ],
                    sort: [
                        {required: true, message: '请输入排序',trigger: 'blur'}
                    ],
                },
            }
        },
        mounted() {
            this.loadDataScopeOptions()
        },
        methods:{

            handleClose() {
                this.dialogVisible=false
                this.loadingSave=false
                this.formData = {
                    id: null,  // 重置ID字段
                    name:'',
                    key:'',
                    description:'',
                    data_scope:'dept',  // 默认部门权限
                    status:true,
                    sort:0,
                }
            },

            addRoleFn(item,flag) {
                this.dialogVisible=true
                this.dialogTitle=flag
                
                if(item && item.id){
                    // 编辑时，确保字段正确映射并验证ID存在
                    this.formData = {
                        id: item.id,
                        name: item.name || '',
                        key: item.key || '',
                        description: item.description || '',
                        data_scope: item.data_scope || 'dept',
                        status: item.status !== undefined ? item.status : true,
                        sort: item.sort || 0,
                    }
                } else {
                    // 新增时使用默认值
                    this.formData = {
                        id: null,  // 新增时ID为null
                        name:'',
                        key:'',
                        description:'',
                        data_scope:'dept',
                        status:true,
                        sort:0,
                    }
                }
            },
            submitData() {
                this.$refs['rulesForm'].validate(obj=>{
                    if(obj) {
                        // 准备提交数据，确保类型正确
                        const submitData = {
                            name: this.formData.name,
                            key: this.formData.key,
                            description: this.formData.description,
                            data_scope: this.formData.data_scope,
                            status: this.formData.status,
                            sort: this.formData.sort
                        }
                        
                        this.loadingSave=true
                        if(this.dialogTitle=="新增" || !this.formData.id){
                            apiSystemRoleAdd(submitData).then(res=>{
                                this.loadingSave=false
                                if(res.code == 200) {
                                    this.$message.success(res.message)
                                    this.handleClose()
                                    this.$emit('refreshData')
                                } else {
                                    this.$message.warning(res.message)
                                }
                            }).catch(error => {
                                this.loadingSave=false
                                console.error('新增角色失败:', error)
                                this.$message.error('新增角色失败，请重试')
                            })
                        }else{
                            if(!this.formData.id) {
                                this.loadingSave=false
                                this.$message.error('角色ID不存在，无法编辑')
                                return
                            }
                            
                            apiSystemRoleEdit(this.formData.id, submitData).then(res=>{
                                this.loadingSave=false
                                if(res.code == 200) {
                                    this.$message.success(res.message)
                                    this.handleClose()
                                    this.$emit('refreshData')
                                } else {
                                    this.$message.warning(res.message)
                                }
                            }).catch(error => {
                                this.loadingSave=false
                                console.error('编辑角色失败:', error)
                                this.$message.error('编辑角色失败，请重试')
                            })
                        }

                    }
                })
            },
            loadDataScopeOptions() {
                apiSystemRoleDataScopeOptions().then(res => {
                    if (res.code === 200) {
                        this.dataScopeOptions = res.data;
                    } else {
                        console.error('加载数据权限选项失败:', res.message);
                    }
                }).catch(error => {
                    console.error('加载数据权限选项时出错:', error);
                });
            }
        }
    }
</script>

